package net.zhengxinyun.performance.service.departClass;

import com.sirdc.modules.utils.ObjectUtils;
import net.zhengxinyun.performance.entity.DepartClass;
import net.zhengxinyun.performance.entity.DepartClassItem;
import net.zhengxinyun.performance.mapper.departClass.DepartClassItemMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class DepartClassItemServiceImpl implements DepartClassItemService {

    @Autowired
    private DepartClassItemMapper mapper;



    @Override
    public List<DepartClassItem> queryItem(DepartClassItem entity) {
        return mapper.queryItem(entity);
    }

    @Override
    public List<DepartClassItem> queryByClassId(Long id) {
        return mapper.queryByClassId(id);
    }

    @Override
    public int update(DepartClassItem entity) {
        return mapper.update(entity);
    }

    @Override
    public int delete(Long id) {
        return mapper.delete(id);
    }

    @Override
    public int saveItems(List<DepartClassItem> list) {
        return mapper.saveItems(list);
    }

    @Override
    public int updateOrSaveWeight(DepartClass entity) {

        List<DepartClassItem> weightList = entity.getWeightList();
        List<DepartClassItem> saveList   = weightList.stream().filter(item -> ObjectUtils.isBlank(item.getId())).collect(Collectors.toList());
        List<DepartClassItem> updateList = weightList.stream().filter(item -> ObjectUtils.isNotBlank(item.getId())).collect(Collectors.toList());

        for (DepartClassItem item : updateList) {
            int update = mapper.update(item);
            if(update==0)
            {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return  0;
            }

        }

        if(ObjectUtils.isNotBlank(saveList))
        {
            saveList.stream().forEach(item -> item.setClassId(entity.getId()));

            int i = mapper.saveItems(saveList);
        }




        return 1;
    }
}
